#include "eparkingmainwindow.h"
#include "./ui_eparkingmainwindow.h"


EParkingMainWindow::EParkingMainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::EParkingMainWindow)
{
    ui->setupUi(this);

    updateTime();
    // 初始化定时器
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &EParkingMainWindow::updateTime);
    timer->start(1000); // 1000毫秒=1秒

    // 初始化LIST模型
    parkingListModel = new QStringListModel(this);
    ui->listView->setModel(parkingListModel);  // listView是Qt Designer中的对象名

    // 初始化停车记录TABLE模型
    parkingRecordsModel = new QStandardItemModel(this);
    ui->tableView_ParkingRecords->setModel(parkingRecordsModel);

    // 设置停车记录TABLE属性
    ui->tableView_ParkingRecords->setSortingEnabled(true);
    ui->tableView_ParkingRecords->horizontalHeader()->setStretchLastSection(true);


    refreshParkingList();//更新库内车列表
    updateStatusText();//更新状态文本
    refreshParkingRecords();//更新停车记录

    // 连接已入库列表点击信号
    connect(ui->listView, &QListView::clicked,
            this, &EParkingMainWindow::onParkingListItemClicked);
    //连接查询框文本修改信号，实现模糊搜索
    connect(ui->textEdit_search, &QTextEdit::textChanged,
            this, &EParkingMainWindow::refreshParkingRecords);

    showFloatingMessage("欢迎使用易停车车库出入库管理系统！");
}

EParkingMainWindow::~EParkingMainWindow()
{
    delete ui;
}



void EParkingMainWindow::showFloatingMessage(const QString &message) {
    QLabel *label = new QLabel(this);
    label->setText(message);
    label->setStyleSheet(QString("  background-color: #f0f6ff; border: 2px solid #90c0ff; "
"  border-radius: 8px;  margin-top: 0px; padding: 16px 16px 16px;            /* 内边距 */"
  "  color: #2a4d7a;     font-family: 微软雅黑;   font-size: 24px; font-weight: 500;"));
    label->setAlignment(Qt::AlignCenter);
    label->adjustSize();

    // 初始位置在屏幕外上方
    int x = (width() - label->width()) / 2;
    label->move(x, -label->height());

    // 显示动画
    QPropertyAnimation *animation = new QPropertyAnimation(label, "pos");
    animation->setDuration(500);
    animation->setStartValue(QPoint(x, -label->height()));
    animation->setEndValue(QPoint(x, 20)); // 移动到顶部下方
    animation->setEasingCurve(QEasingCurve::OutBack);
    animation->start(QAbstractAnimation::DeleteWhenStopped);

    // 3秒后消失
    QTimer::singleShot(3000, label, [=]() {
        QPropertyAnimation *hideAnim = new QPropertyAnimation(label, "pos");
        hideAnim->setDuration(500);
        hideAnim->setStartValue(label->pos());
        hideAnim->setEndValue(QPoint(x, -label->height()));
        hideAnim->start(QAbstractAnimation::DeleteWhenStopped);
        connect(hideAnim, &QPropertyAnimation::finished, label, &QLabel::deleteLater);
    });
}








void EParkingMainWindow::updateStatusText() {
    ui->announce->setText(db.getStatusText());
}

//单击已入库车辆列表，可以把车牌快速输入，方便出库
void EParkingMainWindow::onParkingListItemClicked(const QModelIndex &index)
{
    if (index.isValid()) {
        // 获取车牌号
        QString plate = parkingListModel->data(index).toString();

        ui->textEdit_plate->setPlainText(plate);
    }
}
//单击内部车辆管理按钮 弹出窗口

void EParkingMainWindow::on_pushButton_innercar_window_clicked()
{
    InternalVehicleDialog dialog(this, &db);
    dialog.exec();
}

//单击入库按钮
void EParkingMainWindow::on_pushButton_in_clicked()
{
    // 获取输入车牌
    QString plate = ui->textEdit_plate->toPlainText().trimmed();

    // 用正则表达式验证车牌格式（普通车牌和新能源车牌都可以）
    if (!vehicleValidator.check_plate(plate)) {
        QMessageBox::warning(this, "输入错误",
                             "车牌格式无效！\n正确示例：湘A·12345 或 浙AD23456");
        ui->textEdit_plate->setFocus();
        return;
    }

    // 检查车辆是否已在库
    if (db.isVehicleInParking(plate)) {
        QMessageBox::warning(this, "操作失败",
                             QString("【%1】已在车库中，不可重复入库！").arg(plate));
        return;
    }

    // 执行入库操作
    if (db.logVehicleEntry(plate)) {
        // 更新界面显示
        QMessageBox::information(this, "操作成功",
           QString("【%1】入库成功！").arg(plate));

        ui->textEdit_plate->clear();

        refreshParkingList();//更新
        updateStatusText();//更新
        refreshParkingRecords();
    } else {
        QMessageBox::critical(this, "操作失败",
            "数据库写入失败，请检查系统状态！");
    }
}


void EParkingMainWindow::on_pushButton_out_clicked()
{
    // 获取车牌号
    QString plate = ui->textEdit_plate->toPlainText().trimmed();

    // 用正则表达式验证车牌格式（普通车牌和新能源车牌都可以）
    if (!vehicleValidator.check_plate(plate)) {
        QMessageBox::warning(this, "输入错误",
                             "车牌格式无效！\n正确示例：湘A12345 或 浙AD23456");
        ui->textEdit_plate->setFocus();
        return;
    }

    // 检查是否在库
    if (!db.isVehicleInParking(plate)) {
        QMessageBox::warning(this, "错误", "该车辆未在库内");
        return;
    }

    // 获取停车信息
    QDateTime entryTime = db.getEntryTime(plate);
    if (!entryTime.isValid()) {
        QMessageBox::critical(this, "错误", "无法获取入场时间");
        return;
    }

    // 计算停车时长
    qint64 seconds = entryTime.secsTo(QDateTime::currentDateTime());

    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    int secs = seconds % 60;

    // 判断内部车辆
    bool isInternal = db.isInternalVehicleValid(plate);
    double defaultBill = isInternal ? 0.0 : billCalc.calcBill(seconds);

    // 弹出收费对话框
    bool ok;
    double inputBill = QInputDialog::getDouble(
        this,
        "出库结算",
        QString("长沙市停车收费标准：\n"
        "1. 前2小时免费\n"
        "2. 第3小时起每小时5元\n"
        "3. 24小时内最高收费50元\n\n"
        "车牌号：%1\n停车时长：%2\n是否为内部车辆：%3\n请输入结算金额：")
            .arg(plate)
            .arg(QString("%1小时%2分钟%3秒")
                     .arg(hours).arg(minutes).arg(secs))
            .arg(isInternal? "是":"否"),
        defaultBill,
        isInternal ? 0.0 : 0.0,  // 内部车辆不允许修改 设置最大值0最小值0
        isInternal ? 0.0 : 1000.0,
        2,
        &ok,
        Qt::Dialog,
        isInternal ? Qt::WindowCloseButtonHint : Qt::WindowFlags()
        );

    if (!ok) return;

    // 执行出库操作
    if (db.logVehicleExit(plate, inputBill)) {
        QMessageBox::information(this, "成功", "出库操作完成");

        ui->textEdit_plate->clear();
        refreshParkingList();
        updateStatusText();
        refreshParkingRecords();
    } else {
        QMessageBox::critical(this, "错误", "数据库更新失败");
    }
}

void EParkingMainWindow::updateTime() {
    QTime currentTime = QTime::currentTime();
    QString timeString = currentTime.toString("hh:mm:ss");
    ui->time_LCD->display(timeString);
    QDate currentDate = QDate::currentDate();
    QString dateString = currentDate.toString("yyyy年MM月dd日");
    QString weekDay = QString("星期%1").arg(
        QStringList{"一","二","三","四","五","六","日"}
            .at(currentDate.dayOfWeek()-1));
    ui->time->setText(dateString + " " + weekDay);

}

void EParkingMainWindow::refreshParkingList()
{
    // 获取最新数据
    QList<QString> list = db.getCurrentParkingList();

    // 转换为QStringList
    QStringList stringList = QStringList::fromList(list);

    // 更新模型数据
    parkingListModel->setStringList(stringList);

    // 可选：自动调整列宽
    ui->listView->setUniformItemSizes(true);
}


void EParkingMainWindow::refreshParkingRecords()
{
    // 清空旧数据
    parkingRecordsModel->clear();

    // 获取搜索关键字
    QString keyword = ui->textEdit_search->toPlainText().trimmed();

    // 执行带过滤的查询
    QList<QVariantMap> records = db.getParkingRecords(1000, keyword);


    // 设置中文列头
    QStringList headers = {
        "ID", "车牌号", "入场时间",
        "出场时间", "支付费用", "内部车辆"
    };
    parkingRecordsModel->setHorizontalHeaderLabels(headers);


    // 填充数据
    for (const auto &record : records) {
        QList<QStandardItem*> rowItems;

        // ID列（整型）
        rowItems << new QStandardItem(record["id"].toString());

        // 车牌号
        rowItems << new QStandardItem(record["plate_number"].toString());

        // 时间格式化
        QDateTime entryTime = record["entry_time"].toDateTime();
        QDateTime exitTime = record["exit_time"].toDateTime();
        rowItems << new QStandardItem(entryTime.toString("yyyy-MM-dd hh:mm"));
        rowItems << new QStandardItem(exitTime.isValid() ?
                                          exitTime.toString("yyyy-MM-dd hh:mm") : "未出场");

        // 费用格式化为两位小数
        rowItems << new QStandardItem(QString::number(record["bill"].toDouble(), 'f', 2));

        // 布尔值转中文状态
        rowItems << new QStandardItem(record["is_internal"].toBool() ? "是" : "否");

        // 添加行
        parkingRecordsModel->appendRow(rowItems);
    }

    // 调整列宽更好看
    QHeaderView* header = ui->tableView_ParkingRecords->horizontalHeader();
    header->resizeSection(0, 50);
    header->resizeSection(1, 100);
    header->resizeSection(2, 150);
    header->resizeSection(3, 150);

    header->resizeSection(4, 100);

    header->resizeSection(5, 100);

    // 在refresh函数末尾添加按ID降序排列，新的ID在前面
    parkingRecordsModel->sort(0, Qt::DescendingOrder);
    // 允许用户点击排序
    ui->tableView_ParkingRecords->setSortingEnabled(true);

    ui->tip2->setText(QString("查询到%1条记录").arg(records.count()));
}
